import { Component, OnInit, ViewChild } from '@angular/core';
import { NzFormatEmitEvent } from 'ng-zorro-antd/core';
import { DatePipe } from '@angular/common';
import { RoleManageService } from './role-manage.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzTreeComponent } from 'ng-zorro-antd';
import { HCommonService } from 'src/app/h-common/h-common.service';

@Component({
    selector: 'app-role-manage',
    templateUrl: './role-manage.component.html',
    styleUrls: ['./role-manage.component.scss']
})
export class RoleManageComponent implements OnInit {
    @ViewChild("menuTreeComp", { static: false }) menuTree: NzTreeComponent
    searchValue: string = '';//模糊搜索
    dateRange = [];//日期选择
    pageIndex: number = 1;//提交的页码
    roleForm: FormGroup;
    isOkLoading = false;
    isVisible = false;
    deptData = [];
    editId: number = -1;
    isCheckedAll: boolean = false;
    listOfAllData = [];
    isIndeterminate: boolean = false;
    private deleteRole = [];//删除的角色
    mapOfCheckedId: { [key: string]: boolean } = {};
    pagesize: number = 10;//table每页条数
    totalSize: any = '';//总共条数
    menuNodes = [];
    checkedMenu = [];
    selectedId: number = -1;//选中的行的id
    bornRoles = {}

    modalDomBox: any

    constructor(
        private roleManageService: RoleManageService,
        private datePipe: DatePipe,
        private message: NzMessageService,
        private modalService: NzModalService,
        private fb: FormBuilder,
        private commonService: HCommonService
    ) { }

    ngOnInit() {
        this.modalDomBox = document.querySelector("#modal_box");

        /* 获取权限 */
        this.bornRoles = this.commonService.getRoles("roles");

        this.roleForm = this.fb.group({
            name: [null, Validators.required],
            permission: [null, Validators.required],
            dataScope: ['自定义'],
            depts: [null, Validators.required],
           // level: [null, Validators.required],
            remark: [null],
        })

        this.getSearchList()
        this.getDept()
        this.getAllTreeList('')
    }

    // 日期选择
    onDateChange(result: Date): void {
        let startTime = this.formatDate(result[0])
        let endTime = this.formatDate(result[1])
        this.dateRange = [startTime + " 00:00:00", endTime + " 23:59:59"];
        this.pageIndex = 1;
        this.getSearchList();
    }
    // 时间格式化
    formatDate(date) {
        return this.datePipe.transform(date, 'yyyy-MM-dd');
    }
    hotSearch() {
        this.pageIndex = 1;
        this.getSearchList();
    }
    // 获取列表
    getSearchList() {
        let data = {
            page: this.pageIndex,
            size: this.pagesize,
            blurry: this.searchValue,
            createTime: this.dateRange
        }
        this.roleManageService.getRoles(data).subscribe(res => {
            this.listOfAllData = res.content
            this.totalSize = res.totalElements
        })

    }
    // 点击分页事件
    clickPage(pageIndex) {
        this.pageIndex = pageIndex;
        this.getSearchList()
    }
    // 获取部门数据列表
    getDept() {
        this.roleManageService.getDepartNodes().subscribe(res => {
            this.deptData = this.initHtree(res.content)
        })
    }
    // 初始化部门树
    initHtree(data) {
        if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
                data[i].title = data[i].name || data[i].label;
                data[i].key = data[i].id;
                if (data[i].children) {
                    this.initHtree(data[i].children)
                }
                else {
                    // data[i].children.forEach(res => { res.disableCheckbox = true; res.expanded = true });
                    // data[i].disableCheckbox=true;
                    data[i].expanded=true;
                    data[i].isLeaf = true;
                }

            }
        }
        return data
    }
    checkAll(value: boolean): void {
        this.listOfAllData.forEach(item => {
            this.mapOfCheckedId[item.id] = value
        });
        this.isIndeterminate = false;
        this.filterDelData();
    }

    refreshStatus(): void {
        this.isCheckedAll = this.listOfAllData.every(item => {
            return this.mapOfCheckedId[item.id]
        });
        this.isIndeterminate = this.listOfAllData.some(item => {
            return this.mapOfCheckedId[item.id] && !this.isCheckedAll
        })
        this.filterDelData();
    }
    filterDelData() {
        this.deleteRole = [];
        for (const key in this.mapOfCheckedId) {
            const item = this.mapOfCheckedId[key];
            if (item) {
                this.deleteRole.push(key)
            }
        }
    }

    showModal(type): void {
        this.isVisible = true;
        if (type == 1) {
            this.editId = -1;
            this.roleForm.reset({
                dataScope: "自定义"
            })
        }
        if (type == 2) {
            let _data = this.listOfAllData.filter((item) => {
                return item.id == this.deleteRole[0]
            })[0];
            let eef=_data.depts[0];
            this.editId = _data.id;
            this.roleForm.patchValue({
                name: _data.name,
                permission: _data.permission,
                depts: _data.depts.length!=0?_data.depts[0].id:0,
                //level: _data.level,
                remark: _data.remark,
            })
        }
    }
    handleCancel(): void {
        this.isVisible = false;
    }
    submitFn() {
        let _dataJson = {}
        for (const i in this.roleForm.controls) {
            this.roleForm.controls[i].markAsDirty();
            this.roleForm.controls[i].updateValueAndValidity();
            _dataJson[i] = this.roleForm.controls[i].value
        }
        if (this.roleForm.status === "VALID") {
            if (this.editId == -1) {
                this.add(_dataJson);
            } else {
                this.edit(_dataJson);
            }
        }
    }
    initStatus() {
        this.pageIndex = 1;
        this.mapOfCheckedId = {}
        this.deleteRole = []
        this.isCheckedAll = this.isIndeterminate = false;
        this.getSearchList();
    }
    add(data) {
        this.roleManageService.apiAdd(data).subscribe(res => {
            this.isVisible = false;
            this.initStatus();
        })
    }
    edit(data) {
        let _dataJson = {
            ...data,
            id: this.editId
        }
        this.roleManageService.apiEdit(_dataJson).subscribe(res => {
            this.isVisible = false;
            this.initStatus();
        })
    }

    deleteMore() {
        this.modalService.confirm({
            nzTitle: '确定要删除这些角色吗？',
            nzContent: '',
            nzOkText: '确认',
            nzCancelText: '取消',
            nzOnOk: () => {
                this.roleManageService.apiDelete(this.deleteRole).subscribe(res => {
                    this.initStatus();
                })
            }
        });
    }

    getAllTreeList(ids?) {
        this.roleManageService.apiGetAllMenu().subscribe(res => {
            if (ids) {
                let _data = this.bindMenuData(this.initHtree(res), ids);
                this.menuNodes = _data;
            } else {
                this.menuNodes = this.initHtree(res);
            }
        })
    }
    //刷新菜单分配列表
    getMenu(data) {
        this.selectedId = data.id;
        let menus = data.menus;
        let ids = [];
        for (let i = 0; i < menus.length; i++) {
            ids.push(menus[i].id)
        }
        this.getAllTreeList(ids);
    }
    bindMenuData(data, editIds) {
        if (data.length > 0) {
            data.forEach(item => {
                if (editIds.indexOf(item.id) > -1) {
                    item.checked = true;
                } else {
                    item.checked = false;
                }
                if (item.children) {
                    this.bindMenuData(item.children, editIds)
                }
            })
        }
        return data;
    }
    getAllCheckedMenu(data, arr) {
        if (data.length > 0) {
            data.forEach(item => {
                if (item._isChecked || item._isHalfChecked) {
                    arr.push({
                        id: item.key
                    })
                    if (item.children) {
                        this.getAllCheckedMenu(item.children, arr)
                    }
                }
            })
        }
    }
    saveMenuEdit() {
        let _checkedNodes = this.menuTree.getCheckedNodeList();
        // let _halfCheckedNodes = this.menuTree.getHalfCheckedNodeList();
        let _checkedIds = [];
        this.getAllCheckedMenu(_checkedNodes, _checkedIds);
        // this.getAllCheckedMenu(_halfCheckedNodes, _checkedIds);
        let _dataJson = {
            id: this.selectedId,
            menus: _checkedIds
        }
        this.modalService.confirm({
            nzTitle: '确定提交吗？',
            nzContent: '',
            nzOkText: '确认',
            nzCancelText: '取消',
            nzOnOk: () => {
                this.roleManageService.putRoleMenu(_dataJson).subscribe(res => {
                    this.selectedId = -1;
                    this.getSearchList();
                    this.getAllTreeList();
                    this.message.info("修改成功")
                })
            }
        })
    }
}
